<template>
  <v-card
    ref="rootRef"
    class="mb-4 composer-card"
    :class="{ 'composer-expanded': composerExpanded }"
    elevation="2"
    :ripple="false"
    tabindex="-1"
    @click="handleComposerClick"
  >
    <!-- 输入框区域 -->
    <v-card-text class="px-3 pb-3 pt-0">
      <v-textarea
        ref="composerRef"
        v-model="composerContent"
        auto-grow
        density="comfortable"
        hide-details
        :placeholder="t('whatsOnYourMind')"
        :rows="1"
        variant="plain"
        @keydown.ctrl.enter.prevent="handleComposerSubmit"
      />
    </v-card-text>

    <!-- 展开后的功能区 -->
    <transition name="expand">
      <div v-if="composerExpanded" class="composer-expanded-content">
        <v-divider />

        <!-- 已选择的附件预览 - 图片 -->
        <v-card-text v-if="selectedImages.length > 0" class="ma-2 pa-0">
          <div class="d-flex flex-wrap ga-2">
            <v-chip
              v-for="(img, index) in selectedImages"
              :key="index"
              closable
              color="primary"
              variant="tonal"
              @click:close="removeImage(index)"
            >
              <v-icon :icon="mdiImage" size="small" start />
              {{ img.name }}
            </v-chip>
          </div>
        </v-card-text>

        <!-- 已选择的附件预览 - 文件 -->
        <v-card-text v-if="selectedFiles.length > 0" class="ma-2 pa-0">
          <div class="d-flex flex-wrap ga-2">
            <v-chip
              v-for="(file, index) in selectedFiles"
              :key="index"
              closable
              color="info"
              variant="tonal"
              @click:close="removeFile(index)"
            >
              <v-icon :icon="mdiPaperclip" size="small" start />
              {{ file.name }}
            </v-chip>
          </div>
        </v-card-text>

        <!-- 已选择的标签预览 -->
        <v-card-text v-if="selectedTags.length > 0" class="pa-3 pt-2">
          <div class="d-flex flex-wrap ga-2">
            <v-chip
              v-for="(tag, index) in selectedTags"
              :key="index"
              closable
              size="small"
              variant="outlined"
              @click:close="removeTag(index)"
            >
              <v-icon :icon="mdiTag" size="small" start />
              {{ tag }}
            </v-chip>
          </div>
        </v-card-text>

        <v-divider />

        <!-- 操作栏 -->
        <v-card-actions class="px-3 py-2">
          <v-btn color="success" size="small" variant="text" @click="handleAddImage">
            <v-icon :icon="mdiImage" size="small" start />
            {{ t('addImage') }}
          </v-btn>

          <v-btn color="info" size="small" variant="text" @click="handleAddFile">
            <v-icon :icon="mdiPaperclip" size="small" start />
            {{ t('addFile') }}
          </v-btn>

          <v-btn color="primary" size="small" variant="text" @click="handleAddTag">
            <v-icon :icon="mdiTag" size="small" start />
            {{ t('addTag') }}
          </v-btn>

          <v-spacer />

          <v-btn size="small" variant="text" @click.stop="handleComposerCancel">
            {{ t('cancel') }}
          </v-btn>

          <v-btn
            color="primary"
            :disabled="!composerCanSubmit || composerSubmitting"
            :loading="composerSubmitting"
            size="small"
            variant="elevated"
            @click="handleComposerSubmit"
          >
            {{ t('post') }}
          </v-btn>
        </v-card-actions>
      </div>
    </transition>
  </v-card>
</template>

<script lang="ts" setup>
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { mdiImage, mdiPaperclip, mdiTag } from '@mdi/js'
import type { CreateNoteInput, Note, NoteType } from '../types'

const props = defineProps<{
  createNote: (input: CreateNoteInput) => Promise<Note>
  noteType?: NoteType
}>()
const emit = defineEmits<{ (e: 'submitted', note: Note): void }>()
const { t } = useI18n()

const rootRef = ref()
const composerRef = ref()
const composerContent = ref('')
const composerSubmitting = ref(false)
const composerExpanded = ref(false)
const composerCanSubmit = computed(() => composerContent.value.trim().length > 0)

// 附件和标签
const selectedImages = ref<{ name: string; file?: File }[]>([])
const selectedFiles = ref<{ name: string; file?: File }[]>([])
const selectedTags = ref<string[]>([])

function handleComposerClick() {
  if (!composerExpanded.value) {
    composerExpanded.value = true
    nextTick(() => {
      focus()
    })
  }
}

function handleComposerCancel() {
  composerContent.value = ''
  selectedImages.value = []
  selectedFiles.value = []
  selectedTags.value = []
  composerExpanded.value = false
}

// 点击外部自动收起（在无内容/无附件/无标签时）
function handleClickOutside(event: MouseEvent) {
  if (!composerExpanded.value) return
  const el = (rootRef.value?.$el || rootRef.value) as HTMLElement | undefined
  if (
    el &&
    !el.contains(event.target as Node) &&
    !composerContent.value.trim() &&
    selectedImages.value.length === 0 &&
    selectedFiles.value.length === 0 &&
    selectedTags.value.length === 0
  ) {
    composerExpanded.value = false
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})

// 提交
async function handleComposerSubmit() {
  if (!composerCanSubmit.value || composerSubmitting.value) return
  try {
    composerSubmitting.value = true

    const attachments = [
      ...selectedImages.value.map(img => img.name),
      ...selectedFiles.value.map(file => file.name)
    ]

    const payload: CreateNoteInput = {
      type: props.noteType ?? 'note',
      content: composerContent.value.trim(),
      tags: selectedTags.value.length > 0 ? selectedTags.value : undefined,
      attachments: attachments.length > 0 ? attachments : undefined
    }

    const newNote = await props.createNote(payload)
    emit('submitted', newNote)
    handleComposerCancel()
  } catch (error) {
    console.error('创建记录失败:', error)
  } finally {
    composerSubmitting.value = false
  }
}

function focus() {
  composerRef.value?.focus?.()
}

defineExpose({ focus })

// 附件管理
function handleAddImage() {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.multiple = true
  input.addEventListener('change', (e: Event) => {
    const files = (e.target as HTMLInputElement).files
    if (files) {
      selectedImages.value.push(...Array.from(files).map(file => ({ name: file.name, file })))
    }
  })
  input.click()
}

function handleAddFile() {
  const input = document.createElement('input')
  input.type = 'file'
  input.multiple = true
  input.addEventListener('change', (e: Event) => {
    const files = (e.target as HTMLInputElement).files
    if (files) {
      selectedFiles.value.push(...Array.from(files).map(file => ({ name: file.name, file })))
    }
  })
  input.click()
}

function handleAddTag() {
  const tag = prompt(t('enterTag'))
  if (tag && tag.trim() && !selectedTags.value.includes(tag.trim())) {
    selectedTags.value.push(tag.trim())
  }
}

const removeImage = (index: number) => selectedImages.value.splice(index, 1)
const removeFile = (index: number) => selectedFiles.value.splice(index, 1)
const removeTag = (index: number) => selectedTags.value.splice(index, 1)
</script>

<style scoped>
/* 输入框卡片样式 */
.composer-card {
  position: relative;
  border: 2px solid transparent;
  transition:
    border-color 0.3s cubic-bezier(0.4, 0, 0.2, 1),
    box-shadow 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.composer-card.composer-expanded {
  border-color: rgb(var(--v-theme-primary));
  box-shadow: 0 4px 16px rgba(var(--v-theme-primary), 0.2) !important;
}

/* 展开动画 */
.expand-enter-active,
.expand-leave-active {
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.expand-enter-from,
.expand-leave-to {
  max-height: 0 !important;
  opacity: 0;
}

.expand-enter-to,
.expand-leave-from {
  max-height: 52px !important;
  opacity: 1;
}

.composer-expanded-content {
  max-height: 500px;
}
</style>

<i18n>
{
  "zhHans": {
    "whatsOnYourMind": "写点什么...",
    "post": "发布",
    "cancel": "取消",
    "addImage": "图片",
    "addFile": "文件",
    "addTag": "标签",
    "enterTag": "请输入标签名称"
  },
  "en": {
    "whatsOnYourMind": "What's on your mind...",
    "post": "Post",
    "cancel": "Cancel",
    "addImage": "Image",
    "addFile": "File",
    "addTag": "Tag",
    "enterTag": "Enter tag name"
  }
}
</i18n>
